package com.cinyi.ormlite.web.dao;

import java.sql.Connection;

import com.cinyi.ormlite.core.BaseModel;
import com.cinyi.ormlite.dao.AbstractGenericDaoImpl;
import com.cinyi.ormlite.web.dcp.DbConnectionManager;
import com.cinyi.ormlite.web.util.DbUtil;

/**
 * 泛型DAO的JDBC实现
 * @author penghui
 * @param <T>
 */
@SuppressWarnings("rawtypes")
public class JdbcGenericDaoImpl<T extends BaseModel> extends AbstractGenericDaoImpl<T> {
	private String schema = null ;
	
	/**
	 * 当前数据库连接
	 */
	private ThreadLocal<Connection> connThreadLocal = new ThreadLocal<Connection>();
	
	public JdbcGenericDaoImpl(String schema){
		this.schema = schema ;
		JdbcDatabaseAdapter<T> adapter = new JdbcDatabaseAdapter<T>(this);
		setDatabaseAdapter(adapter);
	}
	
	/**
	 * 获取连接，如果缓存没有则从连接池获取
	 */
	public Connection getConnection() {  
        if (connThreadLocal.get() == null) {
            Connection conn = _getConnection(schema) ; 
            connThreadLocal.set(conn);  
            return conn;  
        } else {  
            return connThreadLocal.get();// ③直接返回线程本地变量  
        }  
    } 
	
	@Override
	public void close(){
	    if( connThreadLocal.get() != null ){
	        Connection conn = connThreadLocal.get();
	        DbUtil.closeConnection(conn);
	    }
	}

	/**
	 * 从连接池获取数据库连接
	 * @param schema
	 * @return
	 */
	private synchronized Connection _getConnection(String schema) {
		return DbConnectionManager.getInstance().getConnection(schema);
	}
	
}
